package com.hl.secondHand.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hl.secondHand.common.dto.LoginDto;
import com.hl.secondHand.common.lang.Result;
import com.hl.secondHand.entity.User;
import com.hl.secondHand.service.IUserService;
import com.hl.secondHand.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {
    @Autowired
    IUserService userservice;
    @Autowired
    JwtUtil jwtUtil;

    @RequestMapping("/login")
    public Result login(@Validated LoginDto dto, HttpServletResponse response) {   //如果可以进入，那么必定是都不为空的
        User user = userservice.getOne(new QueryWrapper<User>().eq("name", dto.getName()));//使用条件构造器匹配用户名，相当于where
        Assert.notNull(user, "用户不存在");   //断言工具类
        System.out.println(SecureUtil.md5(dto.getPassword()));
        Assert.isTrue(user.getPassword().equals(SecureUtil.md5(dto.getPassword())),"密码不正确");
        String jwt = jwtUtil.generateToken(user.getId());
        response.setHeader("Authorization", jwt);
        return Result.succes(jwt);
    }

    @RequestMapping("/logout")
    public Result logout() {
        return Result.succes(null);
    }

    @RequestMapping("/getHeader")
    public Result getHeader(HttpServletResponse response) {
        String authorization = response.getHeader("Authorization");
        return Result.succes(authorization);
    }
}
